﻿using FlyingEye.DeviceMonitor;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Volo.Abp.Uow;

public class TimedHostedService : BackgroundService, IDisposable
{
    private readonly ILogger<TimedHostedService> _logger;

    private readonly IServiceScopeFactory _factory;

    public TimedHostedService(ILogger<TimedHostedService> logger, IServiceScopeFactory factory)
    {
        _logger = logger;
        _factory = factory;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Timed Hosted Service running.");

        using PeriodicTimer timer = new(TimeSpan.FromMilliseconds(100));

        try
        {
            while (await timer.WaitForNextTickAsync(stoppingToken))
            {
                await DoWork();
            }
        }
        catch (OperationCanceledException)
        {
            _logger.LogInformation("Timed Hosted Service is stopping.");
            // lanxiaofang to do
        }
    }

    // Could also be a async method, that can be awaited in ExecuteAsync above
    private async Task DoWork()
    {
        //await Console.Out.WriteLineAsync("Timed Hosted Service is working.");
        using var scope = _factory.CreateScope();
        var service = scope.ServiceProvider;
        var uowManager = scope.ServiceProvider.GetRequiredService<IUnitOfWorkManager>();

        using (var uow = uowManager.Begin(new AbpUnitOfWorkOptions()))
        {
            var monitorService = service.GetRequiredService<DeviceMonitorService>();
            await monitorService.ExecuteMonitorTasksAsync();
            await uow.CompleteAsync();
        }
    }
}